<template>
  <div>
    <Form :model="formState" name="validate_other" ref="formRef" layout="inline">
      <FormItem name="timeRange" label="时间范围">
        <RangePicker
          v-model:value="timeRange"
          :format="format"
          :show-time="showTimeRef"
          :ranges="timeRangeOptions"
          :disabledDate="disabledDate"
          @change="onTimeRangeChange"
          @calendarChange="onCalendarChange"
          @openChange="onOpenChange"
          style="width: 410px"
        ></RangePicker>
      </FormItem>
      <FormItem name="service" label="服务">
        <Select
          v-model:value="formState.service"
          placeholder="请选择服务"
          :options="serviceOptions"
          :allowClear="true"
          @change="onServiceChange"
          style="width: 250px"
        >
        </Select>
      </FormItem>
      <FormItem name="endpoint" label="端点">
        <Select
          v-model:value="formState.endpoint"
          placeholder="请选择端点"
          :options="endpointOptions"
          :allowClear="true"
          style="width: 250px"
          label-in-value
        >
        </Select>
      </FormItem>

      <FormItem>
        <Tooltip title="查询">
          <Button type="primary" @click="search" shape="circle"
            ><template #icon><SearchOutlined /></template
          ></Button>
        </Tooltip>
        <Tooltip title="重置">
          <Button style="margin-left: 10px" @click="reset" shape="circle"
            ><template #icon><RedoOutlined /></template
          ></Button>
        </Tooltip>
      </FormItem>
      <div class="btn-wrapper">
        <Button v-per="'add'" class="editable-add-btn" type="dashed" @click="handleAdd"
          ><template #icon><PlusOutlined /></template>新建任务</Button
        >
      </div>
    </Form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue';
import moment from 'moment';
import { Button, Form, FormItem, Select, RangePicker, Tooltip } from 'ant-design-vue';
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue';
import dayjs, { Dayjs } from 'dayjs';
import { getEndpoint, getService } from '/@/api/maintenance-center/skywalking/trace/trace';
import { PlusOutlined } from '@ant-design/icons-vue';
const formRef = ref();
const showTimeRef = ref(true);

const formState = reactive({
  service: undefined,
  endpoint: { value: undefined },
});

const endpointOptions = ref<any[]>([]);
const serviceOptions = ref<any[]>([]);

type RangeValue = [Dayjs, Dayjs];
const timeRange = ref<RangeValue>();
const timeRangeOptions = {
  最近15分钟: [dayjs().subtract(15, 'minute'), dayjs()] as RangeValue,
  最近30分钟: [dayjs().subtract(30, 'minute'), dayjs()] as RangeValue,
  最近1小时: [dayjs().subtract(1, 'hour'), dayjs()] as RangeValue,
  最近1天: [dayjs().subtract(1, 'day'), dayjs()] as RangeValue,
  最近1周: [dayjs().subtract(1, 'week'), dayjs()] as RangeValue,
  最近1月: [dayjs().subtract(1, 'month'), dayjs()] as RangeValue,
  最近2月: [dayjs().subtract(2, 'month'), dayjs()] as RangeValue,
};
const format = ref<string>('YYYY-MM-DD HH:mm:ss');

const stepFormatMap = {
  SECOND: 'YYYY-MM-DD HHmmss',
  MINUTE: 'YYYY-MM-DD HHmm',
  HOUR: 'YYYY-MM-DD HH',
  DAY: 'YYYY-MM-DD',
  MONTH: 'YYYY-MM',
};

let disabledCurrent: any = null;
let isHandOperated = false;
function onOpenChange(status: boolean) {
  if (status) {
    disabledCurrent = timeRange.value;
  } else {
    disabledCurrent = null;
  }
}

function onCalendarChange(dates: [Dayjs, Dayjs]) {
  if (dates && dates[0] && dates[1]) {
    return;
  }
  if (dates !== null) {
    isHandOperated = true;
    disabledCurrent = dates;
    return;
  }
}

function disabledDate(current: Dayjs) {
  if (!disabledCurrent) {
    return false;
  }
  if (disabledCurrent[0] && disabledCurrent[1]) {
    return (
      current && (current > disabledCurrent[0].add(2, 'month') || current < disabledCurrent[1].subtract(2, 'month'))
    );
  }
  if (disabledCurrent[0]) {
    return current && current > disabledCurrent[0].add(2, 'month');
  }
  if (disabledCurrent[1]) {
    return current && current < disabledCurrent[1].subtract(2, 'month');
  }
}

let durationParam = {
  start: '',
  end: '',
  step: '',
};

function processDuration(startTime: moment.Moment, endTime: moment.Moment, step: string) {
  if (startTime.second() !== endTime.second() && !isHandOperated) {
    step = 'SECOND';
    durationParam.start = startTime.format(stepFormatMap.SECOND);
    durationParam.end = endTime.format(stepFormatMap.SECOND);
  } else if (startTime.minute() !== endTime.minute() && !isHandOperated) {
    step = 'MINUTE';
    durationParam.start = startTime.format(stepFormatMap.MINUTE);
    durationParam.end = endTime.format(stepFormatMap.MINUTE);
  } else if (startTime.hour() !== endTime.hour()) {
    step = 'HOUR';
    durationParam.start = startTime.format(stepFormatMap.HOUR);
    durationParam.end = endTime.format(stepFormatMap.HOUR);
  } else if (startTime.day() !== endTime.day()) {
    step = 'DAY';
    durationParam.start = startTime.format(stepFormatMap.DAY);
    durationParam.end = endTime.format(stepFormatMap.DAY);
  } else {
    step = 'DAY';
    durationParam.start = startTime.format(stepFormatMap.DAY);
    durationParam.end = endTime.format(stepFormatMap.DAY);
  }

  durationParam.step = step;
  return durationParam;
}

let serviceParams = {
  duration: durationParam,
  keyword: '',
};
// 获取服务列表
const getServiceData = async () => {
  serviceOptions.value = await getService(serviceParams);
};

let navParams = {
  endpointName: formState.endpoint.label,
  serviceId: formState.service,
};
// 清空formState
const clearFormState = (updateService?) => {
  if (updateService == true) {
    formState.endpoint = undefined;
    endpointOptions.value = [];
  } else {
    formState.service = undefined;
    formState.endpoint = undefined;
    endpointOptions.value = [];
  }
};
// 刷新当前navParams
const refreshNavParams = () => {
  if (formState.endpoint) {
    navParams = {
      endpointName: formState.endpoint.label,
      serviceId: formState.service,
    };
  } else {
    navParams = {
      endpointName: formState.endpoint,
      serviceId: formState.service,
    };
  }
};
const emit = defineEmits(['get', 'new', 'clear']);
const onServiceChange = async (data) => {
  clearFormState(true);
  refreshNavParams();
  if (data !== null && data != '' && data != undefined) {
    let endpointParams = {
      serviceId: data,
      keyword: '',
      limit: 100,
    };
    endpointOptions.value = await getEndpoint(endpointParams);
  } else {
    emit('clear');
    clearFormState();
  }
};
// 时间范围选择好
const onTimeRangeChange = (data) => {
  clearFormState();
  refreshNavParams();
  serviceOptions.value = [];
  if (data !== null && data != undefined && data.length != 0) {
    let startTime = data[0];
    let endTime = data[1];
    let step = '';
    durationParam = processDuration(startTime, endTime, step);
    serviceParams.duration = durationParam;
    getServiceData();
  } else {
    formState.service = undefined;
    onServiceChange(null);
  }
  isHandOperated = false;
};
// 新建任务
const handleAdd = () => {
  emit('new', { endpointOptions: endpointOptions.value, serviceId: formState.service });
};
// 监听端点
watchEffect(() => {
  if (!formState.endpoint) {
    emit('clear');
  }
});
// 提交表单参数
const search = async () => {
  formRef.value.validate();
  refreshNavParams();
  emit('get', navParams);
};

// 清空表单参数
const reset = () => {
  formRef.value.clearValidate();
  timeRange.value = [];
  onTimeRangeChange(null);
};
</script>
<style lang="less">
.btn-wrapper {
  display: flex;
  justify-content: flex-end;
  flex: 1;
  padding: 0px 20px;
}
</style>
